package com.chinacoal.microservice.service.impl;

import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.mapper.CcmsSmartleasingRepairMapper;
import com.chinacoal.microservice.pojo.CcmsSmartleasingRepair;
import com.chinacoal.microservice.pojo.Currency;
import com.chinacoal.microservice.service.MaintenanceRecordsService;
import com.chinacoal.microservice.util.CodeMsg;
import com.chinacoal.microservice.util.QueryCriteria;
import com.chinacoal.microservice.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author zhuliang
 * @version V1.0
 * @Description: 房源管理-维修记录-实现类
 * @date 2020-11-10 14：00
 */
@Slf4j
@Service
public class MaintenanceRecordsServiceImpl implements MaintenanceRecordsService {

    @Autowired
    private CcmsSmartleasingRepairMapper repairMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @Description: 查询所有的维修记录（带分页）
     * @author zhuliang
     * @date 2020/11/10 14:04
     */
    @Override
    public Result<List<CcmsSmartleasingRepair>> getMaintenanceRecords(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingRepair> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //得到维修记录信息
        List<CcmsSmartleasingRepair> repairList = repairMapper.getAllByPage(toPage, currency.getProperty(), currency.getManagementOffice());

        return Result.success(repairList,toPage.getTotal());
    }

    /**
     * @Description: 根据维修信息id查询对应的信息
     * @author zhuliang
     * @date 2020/11/10 14:19
     */
    @Override
    public Result<CcmsSmartleasingRepair> getMaintenanceById(String pkRepairId, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //根据维修id查询维修信息
        CcmsSmartleasingRepair repair = repairMapper.getRepairById(pkRepairId, currency.getProperty(), currency.getManagementOffice());

        //拆分地址，并做兼容性处理
        if (repair != null) {
            if (StringUtils.isNotBlank(repair.getScenePhotos())) {
                String[] photosList = repair.getScenePhotos().split(",");
                repair.setScenePhotosList(photosList);
            }
        } else {
            log.error(CodeMsg.NOT_FOUND.toString() + "-->此维修信息无权限访问，或数据丢失-->" + pkRepairId);
            return Result.error(CodeMsg.NOT_FOUND);
        }


        return Result.success(repair);
    }

    /**
     * @Description: 添加维修信息
     * @author zhuliang
     * @date 2020/11/10 14:30
     */
    @Override
    public Result addMaintenanceRecords(CcmsSmartleasingRepair repair, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置默认的添加参数
        repair.setPkRepairId(UUID.randomUUID() + "");
        repair.setCreationDate(new Date());
        repair.setLastUpdateDate(new Date());
        repair.setCreatedBy(currency.getLoginId());
        repair.setLastUpdatedBy(currency.getLoginId());

        //添加维修信息
        repairMapper.insert(repair);

        return Result.success();
    }

    /**
     * @Description: 修改维修信息
     * @author zhuliang
     * @date 2020/11/10 14:37
     */
    @Override
    public Result updateMaintenanceRecords(CcmsSmartleasingRepair repair, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置最后修改的时间和修改人
        repair.setLastUpdateDate(new Date());
        repair.setLastUpdatedBy(currency.getLoginId());

        //根据维修信息id进行修改
        repairMapper.updateById(repair);

        return Result.success();
    }

    /**
     * @Description: 根据维修信息id批量删除对应的维修信息
     * @author zhuliang
     * @date 2020/11/10 14:43
     */
    @Override
    public Result delectMaintenanceRecords(String deleteId, String token) {
        //得到登录人id
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //将传入的维修信息id集的字符串进行拆分处理
        String[] ids = deleteId.split(",");

        //进行批量修改
        repairMapper.updateToDeleteById("1",
                                        new Date(),
                                        ids,
                                        currency.getLoginId(),
                                        currency.getProperty(),
                                        currency.getManagementOffice());

        return Result.success();
    }

    /**
     * @Description: 条件查找维修信息（带分页）
     * @author zhuliang
     * @date 2020/11/10 16:08
     */
    @Override
    public Result<List<CcmsSmartleasingRepair>> queryMaintenanceRecords(QueryCriteria queryCriteria, String token) {
        //得到登录人信息
        Currency currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getSignature());
        if (null == currency) {
            currency = (Currency) redisTemplate.opsForValue().get("ccms:" + JWT.decode(token).getClaim("phone").asString());
        }

        //设置分页查询条件
        Page<CcmsSmartleasingRepair> toPage = new Page<>(queryCriteria.getPage(), queryCriteria.getPageSize());

        //兼容性处理
        if (StringUtils.isNotBlank(currency.getManagementOffice()) && StringUtils.isNotBlank(queryCriteria.getFkAdministrationId())) {
            if (!currency.getManagementOffice().equals(queryCriteria.getFkAdministrationId())) {
                log.error(CodeMsg.NOT_FOUND.toString() + "-->查询条件，无权查询-->" + queryCriteria);
                return Result.error(CodeMsg.NOT_FOUND);
            }
        }

        //开始条件分页查询
        List<CcmsSmartleasingRepair> repairList = repairMapper.getAllByCondition(queryCriteria.getFirstDate(),
                                                                                queryCriteria.getEndDate(),
                                                                                currency.getManagementOffice(),
                                                                                queryCriteria.getInputString(),
                                                                                currency.getProperty(),
                                                                                toPage);

        return Result.success(repairList, toPage.getTotal());
    }
}
